package jk.fox.serializable.kryo;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import jk.fox.serializable.Serialization;

/**
 * @author cuichao
 * @Description: KryoSerialization
 * @Date: create in 2020/4/10 22:01
 */
public class KryoSerialization implements Serialization {

    @Override
    public byte[] serialize(Object object) {
        Kryo kryo = KryoFactory.get();
        Output output = new Output(1024);
        try {
            kryo.writeObjectOrNull(output,object, object.getClass());
            byte[] bytes = output.toBytes();
            return bytes;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            output.flush();
            output.close();
        }

    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> targetClass) {
        Kryo kryo = KryoFactory.get();
        Input input = new Input(bytes);
        try {
            T t = kryo.readObjectOrNull(input, targetClass);
            return t;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            input.close();
        }
    }


    @Override
    public String getContentType() {
        return "x-application/kryo";
    }
}
